<?php
namespace Frieza\Modules\Ifttt\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\Ifttt as sIfttt;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\service\position\PositionApi;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Frieza\Modules\Ifttt\Actions\Check;
use Frieza\Modules\Ifttt\Actions\Copy;
use Frieza\Modules\Ifttt\Actions\DataBoard;
use Frieza\Modules\Ifttt\Actions\Delete;
use Frieza\Modules\Ifttt\Actions\Edit;
use Frieza\Modules\Ifttt\Actions\View;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Box;
use Illuminate\Support\MessageBag;
use Doraemon\model\Ifttt\AdmIftttRule as mAdmIftttRule;
use Doraemon\service\position\UserProfileModule;

class IftttController extends Controller
{
    //触发类型
    const TRIGGER_TYPE_A = 1;  //完成A
    const TRIGGER_TYPE_AB = 2; //完成A未完成B
    const TRIGGER_TYPE_V = 3;  //浏览页面

    const TRIGGER_TYPE_DESC = [
        self::TRIGGER_TYPE_A => "完成A",
        self::TRIGGER_TYPE_AB => "完成A未完成B",
        self::TRIGGER_TYPE_V => "浏览页面",
    ];

    //业务线
    const BUSINESS_WAY_DESC = [
        1 => "设计师",
        2 => "品牌",
        3 => "社区",
        4 => "广告",
        5 => "主产品",
        6 => "增长",
    ];

    const PAGE_SIZE = 20;

    //属性关系
    const EVENT_ATTRIBUTE_TYPE = [
        1 => '大于',
        2 => '小于',
        3 => '小于等于',
        4 => '大于等于',
        5 => '等于',
        6 => '不等于',
        7 => '不为空',
        8 => '为空',
        9 => '包含(多个值使用逗号拼接)',
    ];

    //交互共性
    const SIMILARITY_NONE = 0;   //无
    const SIMILARITY_AUTHOR = 1;  //同一作者
    const SIMILARITY_CONTENT = 2;   //同一内容
    const SIMILARITY_CONTENT_TYPE = 3;   //同一内容类型

    const SIMILARITY_DESC = [
        self::SIMILARITY_NONE => '无',
        self::SIMILARITY_AUTHOR => '同一作者',
        self::SIMILARITY_CONTENT => '同一内容',
        self::SIMILARITY_CONTENT_TYPE => '同一内容类型',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script($this->addScript());
        Admin::disablePjax();
    }

    public function task_list(Request $request, Content $content, $tab_id = 0)
    {
        $tab = new Tab();
        $tab->addLink('全部', url('admin/Ifttt/task_list'), $tab_id == 0);
        $tab->addLink('编辑中', url('admin/Ifttt/task_list/1'), $tab_id == 1);
        $tab->addLink('待审批', url('admin/Ifttt/task_list/2'), $tab_id == 2);
        $tab->addLink('测试中', url('admin/Ifttt/task_list/3'), $tab_id == 3);
        $tab->addLink('测试完成', url('admin/Ifttt/task_list/4'), $tab_id == 4);
        $tab->addLink('上线', url('admin/Ifttt/task_list/5'), $tab_id == 5);
        $tab->addLink('下线', url('admin/Ifttt/task_list/6'), $tab_id == 6);

        Admin::style('.nav-tabs-custom{margin-bottom:0;} .box-header>.pull-left{width: 100%;}');

        $params = $request->input();
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);

        $search = [
            'page' => $page,
            'pageSize' => $pageSize,
        ];
        if ($tab_id) {
            $search['status'] = $tab_id;
        }
        if (isset($params['pushType']) && $params['pushType']) {
            $search['pushType'] = $params['pushType'];
        }
        if (isset($params['pushWay']) && $params['pushWay']) {
            $search['pushWay'] = $params['pushWay'];
        }
        if (isset($params['businessWay']) && $params['businessWay']) {
            $search['businessWay'] = $params['businessWay'];
        }
        if (isset($params['keyWord']) && $params['keyWord']) {
            $search['keyWord'] = $params['keyWord'];
        }

        $list = sIfttt::getTaskListFromRemote($search);
        foreach ($list['list'] as &$item) {
            $item['status_name'] = sIfttt::TASK_STATUS_DESC[$item['status']];
        }
        unset($item);

        $dataList = $list['list'] ?? [];
        $ids = array_column($dataList, 'id');
        $rules = PositionApi::activeRules($ids, PositionRules::MODULE_TYPE_IFTTT_TASK);
        $list['list'] = array_map(function ($v) use ($rules) {
            $v['userprofile'] = $rules[$v['id']] ?? [];
            return $v;
        }, $dataList);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增', 'fa-plus', url('/admin/Ifttt/create_task')));
                });
                $grid->filter(function($filter){
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('pushType', '触发类型')->select(self::TRIGGER_TYPE_DESC);
                        $filter->equal('keyWord', '关键词');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('pushWay', '触发方式')->select(mAdmIftttRule::TYPE_DESC);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('businessWay', '业务线')->select(self::BUSINESS_WAY_DESC);
                    });

                    $filter->expand();
                });

                $grid->column("id", '任务ID');
                $grid->column("taskName", '名称')->width(300);
                $grid->column("createTime", '创建时间');
                $grid->column("status_name", '状态')->display(function ($status_name, $column) {
                    $status = $this->status;
                    if ($status == sIfttt::TASK_STATUS_OFFLINE) {
                        return $status_name;
                    } else {
                        return $column->modal('编辑状态', function () use($status) {
                            $form = new Form();
                            $form->disableReset();
                            $form->disableSubmit();
                            $form->hidden('id')->default($this->id);
                            switch ($status) {
                                case sIfttt::TASK_STATUS_TESTING:
                                    $form->select('status','状态')->options([
                                        sIfttt::TASK_STATUS_CHECKED => "测试完成",
                                        sIfttt::TASK_STATUS_OFFLINE => "下线",
                                    ]);
                                    break;
                                case sIfttt::TASK_STATUS_CHECKED:
                                    $form->select('status','状态')->options([
                                        sIfttt::TASK_STATUS_ONLINE => "上线",
                                        sIfttt::TASK_STATUS_OFFLINE => "下线",
                                    ]);
                                    break;
                                default:
                                    $form->select('status','状态')->options([
                                        sIfttt::TASK_STATUS_OFFLINE => "下线",
                                    ]);
                            }
                            $form->html('<div class="modal-submit"><button type="button" class="btn btn-primary">提交</button></div>')->plain();
                            Admin::style('.modal-submit{text-align: right;padding: 0 23%;}');

                            return new Box("", $form);
                        });
                    }
                });
                $grid->column("pushType", '触发类型')->using(self::TRIGGER_TYPE_DESC);
                $grid->column("pushWayList", '触发方式')->display(function(){
                    $ways = array_map(function ($v) {
                        return mAdmIftttRule::TYPE_DESC[$v];
                    }, $this->pushWayList);
                    return implode("<br/>", $ways);
                });
                $grid->column("createBy", '创建人');
                $grid->column("dataQuota", '数据指标(最近一天)')->display(function () {
                    return str_replace("\n", "<br/>", $this->dataQuota);
                });
                $grid->column("task_time", '起止时间')->display(function() {
                    return $this->taskStartTime . "<br/>". $this->taskEndTime;
                });
                $grid->column('userprofile', '用户分群')->width(200)->userProfile();
                $grid->setActionClass(DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->disableEdit();

                    $actions->add(new Edit);
                    $actions->add(new View);
                    if ($actions->row->status == sIfttt::TASK_STATUS_PENDING && $actions->row->isApprove == 0) {
                        $actions->add(new Check);
                    }
                    if ($actions->row->status == sIfttt::TASK_STATUS_ONLINE) {
                        $actions->add(new DataBoard);
                    }
                    $actions->add(new Copy);
                    if (Admin::user()->can('ifttt-check')) {
                        $actions->add(new Delete);
                    }
                });
            });
        $row = $gridList->render();

        return $content
            ->header('IFTTT管理')
            ->description('任务列表')
            ->breadcrumb(['text' => '任务列表'])
            ->body($tab)
            ->row($row);
    }

    public function create_task(Request $request, Content $content, $id = 0)
    {
        $is_view = false;
        if (stripos($request->path(), 'view') !== false) {
            $is_view = true;
        }
        if (!$is_view) {
            //屏蔽新增和编辑任务
            $error = new MessageBag([
                'title' => '操作失败：请使用新的V3创建和编辑任务'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        $info = [];
        if ($id) {
            $taskInfo = sIfttt::getTaskInfoFromRemote($id);
            $info = $this->formatTaskInfo($taskInfo);
        }
        $form = new Form($info);
        $form->disableReset();
        $form->disableSubmit();
        if ($is_view) {
            $form->disableSubmit();
        }
        if ($id) {
            $form->hidden('id');
        }
        $form->html('<div class="t-head">')->plain();
        $form->html('<div class="col-in-row">')->plain();
        $form->text('task_name', '任务名称')->required()->setWidth(8, 4);
        $form->select('business_way','业务线')->options(self::BUSINESS_WAY_DESC)->required();
        $form->html('</div>')->plain();
        $form->textarea('task_desc','任务描述')->rows(3)->setWidth(9, 2);
        $form->html('</div>')->plain();

        if ($info && $info['status'] == sIfttt::TASK_STATUS_ONLINE && !$is_view) {
            $form->hidden('status');
            $form->dateTimeRange('task_start_time', 'task_end_time', '起止时间')->required();
            $form->fieldGroup('rule_ids', '选择规则', function ($form) use($is_view) {
                $form->select('rule_id', '规则')->options(url('admin/Ifttt/get_select_rules'));
            })->addElementClass("rule-group");
        } else {
            $form->hidden('tab_location')->default(1);
            $form->html('<div class="divide-box"></div>')->plain();

            $html1 = <<<HTML
            <ul class="nav nav-tabs">
                <li class="active" style="padding-right: 30%;">
                    <a href="#tab1" data-toggle="tab">触发时机</a>
                    <div class="tab-tips">
                        <p id="tip1"></p>
                        <p id="tip2"></p>
                    </div>
                </li>
                <li style="padding-right: 30%;"><a href="#tab2" data-toggle="tab">受众用户</a></li>
                <li><a href="#tab3" data-toggle="tab">触达配置</a></li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane fade in active" id="tab1">
HTML;
            $form->html($html1)->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">触发类型</h3></div></div>')->plain();
            $form->radioCard('trigger_type', '')
                ->options(self::TRIGGER_TYPE_DESC)->default($info['trigger_type'] ?? self::TRIGGER_TYPE_A)
                ->when(self::TRIGGER_TYPE_A, function (Form $form) use ($info) {
                    $this->eventModule($form, 1, 'e_a', $info);
                })->when(self::TRIGGER_TYPE_AB, function (Form $form) use ($info) {
                    $this->eventModule($form, 1, 'e_ab_a', $info);
                    $form->divider();
                    $form->number("interval_duration", '且多久未完成事件B')->min(0)->max(604800)->default(0)->help("单位：秒")->setWidth(8, 2);
                    $this->eventModule($form, 2, 'e_ab_b', $info);
                })->when(self::TRIGGER_TYPE_V, function (Form $form) {
                    $form->select("page_type", '页面类型')->options([1=>'文章', 2=>'note', 3=>'整屋', 4=>'任意页面']);
                    $form->number("view_duration", '浏览时长')->min(0)->max(604800)->default(0)->help("单位：秒");
                })->setWidth(10, 0);
            $form->html('<div class="divide-box"></div>')->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">触发条件</h3></div></div>')->plain();
            $form->radio("trigger_opportunity", "触发时机")
                ->options([1=>'立即', 2=>'延迟'])
                ->default($info['trigger_opportunity'] ?? 1)
                ->help("完成后多久触发")
                ->when('=', 2, function (Form $form) {
                    $form->number("delay_time", '秒')->min(0)->default(0);
                });
            $form->select("similarity", "交互共性")
                ->options(self::SIMILARITY_DESC)
                ->default(0)->setWidth(4, 2);
            $form->dateTimeRange('task_start_time', 'task_end_time', '起止时间')->required();

            $html2 = <<<HTML
                    </div>
                    <div class="tab-pane fade" id="tab2">
                        
HTML;
            $form->html($html2)->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">用户划分</h3></div></div>')->plain();
            $form->userProfile('user_profile', '用户分群')->options(UserProfileModule::$other_position_rules)->generate()->setWidth(4, 6);
            $form->html('<div class="divide-box"></div>')->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">行为历史</h3></div></div>')->plain();
            $form->radio("action_relation", "行为关系")->options([1=>'且', 2=>'或'])->default(1)->setWidth(8,2);
            $this->eventModule($form, 3, 'action', $info);
            $form->html('<div class="divide-box"></div>')->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">SQL预估 <i class="fa fa-question-circle" data-type="sql_pre"></i></h3></div></div>')->plain();
            $form->html('<div style="margin: 0 0 22px 5%;font-size: 14px;"><i class="fa fa-info-circle"></i> sql预估耗时可能较长，需等待</div>')->plain();
            $form->text('trigger_users', '可触发人数')->default(0)->setWidth(5,2)->readonly();
            if (!$is_view) {
                $form->html('<div class="prospect"><button type="button" class="btn btn-primary">预估</button></div>')->plain();
                $form->html('<div class="text-right" style="padding: 100px 13% 42px 0;">')->plain();
                if (!empty($info['status'])) {
                    $form->html('<div style="padding-bottom: 15px;">任务状态：<span class="stat">'.sIfttt::TASK_STATUS_DESC[$info['status']].'</span></div>')->plain();
                }
                if ($info && $info['is_approve'] == 1 && Admin::user()->can('ifttt-check')) {
                    $form->html('<input type="submit" class="btn btn-success btn-check" data-id="'.$id.'" value="审核通过" style="width: 94px;margin-left: 35px;" />')->plain();
                }
                $form->html('</div>')->plain();
            }

            $html3 = <<<HTML
                    </div>
                    <div class="tab-pane fade" id="tab3">
HTML;
            $form->html($html3)->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">触达配置</h3></div></div>')->plain();
            if ($id) {
                $form->radioCard('rule_action', " ")
                    ->options([1=>"选择已有规则"])->default(1)
                    ->setWidth(8, 1)
                    ->when(1, function (Form $form) use($is_view, $id, $info) {
                        $form->fieldGroup('rule_ids', '选择规则', function ($form) use($is_view) {
                            $form->select('rule_id', '规则')->options(url('admin/Ifttt/get_select_rules'));
                        })->addElementClass("rule-group");
                        if (!$is_view) {
                            $form->html('<div class="text-right" style="padding: 100px 13% 42px 0;">')->plain();
                            if (!empty($info['status'])) {
                                $form->html('<div style="padding-bottom: 15px;">任务状态：<span class="stat">'.sIfttt::TASK_STATUS_DESC[$info['status']].'</span></div>')->plain();
                            }
                            if ($info && $info['is_approve'] == 1 && Admin::user()->can('ifttt-check')) {
                                $form->html('<input type="submit" class="btn btn-success btn-check" data-id="'.$id.'" value="审核通过" style="width: 94px;margin-left: 35px;" />')->plain();
                            }
                            $form->html('</div>')->plain();
                        }
                    });
            } else {
                $form->radioCard('rule_action', " ")
                    ->options([1=>"选择已有规则", 2=>"新增规则"])->default(1)
                    ->setWidth(8, 1)
                    ->when(1, function (Form $form) {
                        $form->fieldGroup('rule_ids', '选择规则', function ($form) {
                            $form->select('rule_id', '规则')->options(url('admin/Ifttt/get_select_rules'));
                        })->addElementClass("rule-group");
                    })->when(2, function (Form $form) use ($id) {
                        (new IndexController())->ruleForm($form);
                        $form->html('<div class="text-right" style="padding: 10px 241px 42px 0;"><input type="submit" class="btn btn-info btn-save-rule" value="保存规则" /></div>')->plain();
                    });
            }

            $form->html('<div class="divide-box"></div>')->plain();
            $form->html('<div class="divide-box-title"><div class="box-header with-border"><h3 class="box-title">白名单用户</h3></div></div>')->plain();
            $form->textarea('whiteTable','uid')->rows(5)->setWidth(9, 2)->help("多个uid之间用英文逗号[,]分隔");

            $html4 = <<<HTML
                    </div>
                </div>
HTML;
            $form->html($html4)->plain();
        }

        Admin::style('
        .nav-tabs {margin: 0 -20px;}
        .nav-tabs li:before {position: absolute;top: 31%;left: 90px;content: " ";display: inline-block;width: 100%;border: 1px dashed #ccc;}
       
        .nav-tabs{border:none;background: #ecf0f5;text-align: center;}
        .nav-tabs>li {display: inline-block;text-align: center;float:none;margin:0;position: relative;overflow: hidden;padding-bottom: 20px;}
        .nav-tabs>li>a {border-radius: 3px;border: 1px solid #a3a2a2;color: #333;}
        .nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {color: #fff;background-color: #337ab7;border: 1px solid #2e6da4;}
        .nav-tabs>li>a:hover {color: #fff;background-color: #337ab7;border: 1px solid #2e6da4;}
        
        .tab-tips {position: absolute;top: 5px;left: 90px;border: 1px dashed #bbb;padding: 4px 8px;background: #fff;width: 105px;text-align: center;display:none;margin-left: 27%;}
        .tab-tips p {margin-bottom: 0;}
        .event-add-btn {margin-bottom: 10px;}
        .event-kj-title{font-size: 16px;}
        .event-kj {border: 1px solid #ccc;margin: 15px 0;padding: 17px 9px 10px 0px;min-width: 600px;max-width: 100%;}
        .ep-relation {display: none;}
        .con_kj {padding: 17px 0 22px;overflow: hidden;}
        .con_kj>div {display: block;}
        .btn-remove {float: right !important;}
        .condition-add-btn {padding-bottom: 15px;width: 16.66666667%;text-align: right;padding-right: 25px;}
        .prospect {text-align: center;}
        .con_kj>.cascade-group {padding-left: 16.66666667%;width: 100%;overflow: hidden;margin-left: 5px;}
        .con_kj>.cascade-group>div {display: inline-block;width: 40%;float: left;}
        .ekj {padding-bottom: 1px;}
        
        .t-head .form-group{margin: 0 0 15px;}
        .col-in-row .form-group {display: inline-block;width: 50%;float: left;}
        .divide-box {background: #ecf0f5;margin: 0px -20px;padding-top: 25px;}
        .divide-box-title {margin: 0 -20px 15px;border-top: 3px solid #d2d6de;}
        .popover{max-width: 412px;}
        ');

        $form->action(url('admin/Ifttt/save_task'));
        $form->html('<div class="divide-box" style="border-bottom: 3px solid #d2d6de;"></div>')->plain();
//        $form->html('<div class="box-footer"><div class="col-md-12"><div class="btn-group pull-right"><button type="submit" class="btn btn-info pull-right">提交任务</button></div></div></div>');

        $form->confirm('确认提交吗？');
        $title = '创建任务';
        if ($id) {
            $title = $is_view ? '查看任务' : '编辑任务';
        }
        $box = new Box($title, $form);

        return $content
            ->header('IFTTT管理')
            ->description($title)
            ->breadcrumb(
                ['text' => '任务列表', 'url' => url('admin/Ifttt/task_list')],
                ['text' => $title]
            )
            ->row($box);
    }

    /**
     * 事件视图
     * @param  Form $form
     * @param  int $type   类型  1=事件A  2=事件B 3=行为
     * @param  string  $params   参数名
     * @return void
     */
    private function eventModule(Form &$form, $type = 1, $params = '', $info = [])
    {
        switch ($type) {
            case 1:
                $event_title = "事件A";
                break;
            case 2:
                $event_title = "事件B";
                break;
            case 3:
                $event_title = "行为";
                break;
            default:
                return;
        }

        $form->html('<div class="ekj">')->plain();
        $form->html('<div class="many_option-event"><div class="many_option-event-forms">')->plain();
        for ($j=0;$j<10;$j++) {
            if ($j == 0 || ($info && isset($info[$params]) && $j < count($info[$params]))) {
                $form->html('<div class="many_option-event-form fields-group" data-id="'.$j.'">')->plain();
                $event_relation = (3 == $type && $info['action_relation'] == 1) ? "--AND" : "--OR";
                if (1 == $type) {
                    $form->html('<h3 class="event-kj-title" data-title="'.$event_title.'">'.($j ==0 ? $event_title.' <i class="fa fa-question-circle" data-type="event-a"></i>' : $event_relation).'</h3>')->plain();
                } else {
                    $form->html('<h3 class="event-kj-title" data-title="'.$event_title.'">'.($j ==0 ? $event_title : $event_relation).'</h3>')->plain();
                }
                $form->html('<div class="event-kj">')->plain();
                $form->html("<input type='hidden' name='{$params}[{$j}][is_remove]' class='remove form-removed' value='0' />")->plain();
                $form->html('<div class="remove btn btn-warning pull-right"><i class="fa fa-trash"></i>&nbsp;移除'.$event_title.'</div>')->plain();
            } else {
                $form->html('<div class="many_option-event-form fields-group" data-id="'.$j.'" style="display: none;">')->plain();
                if (1 == $type) {
                    $form->html('<h3 class="event-kj-title" data-title="'.$event_title.'">'.$event_title.' <i class="fa fa-question-circle" data-type="event-a"></i></h3>')->plain();
                } else {
                    $form->html('<h3 class="event-kj-title" data-title="'.$event_title.'">'.$event_title.'</h3>')->plain();
                }
                $form->html('<div class="event-kj">')->plain();
                $form->html("<input type='hidden' name='{$params}[{$j}][is_remove]' class='remove form-removed' value='1' />")->plain();
                $form->html('<div class="remove btn btn-warning pull-right"><i class="fa fa-trash"></i>&nbsp;移除'.$event_title.'</div>')->plain();
            }

            if ($type == 3) {
                $form->html('<div class="action-duration">')->plain();
                $form->radio("{$params}.{$j}.duration", '时间类型')
                    ->options([1=>'静态', 2=>'动态'])
                    ->default($info[$params][$j]['duration'] ?? 1)
                    ->when('=', 1, function (Form $form) use($j, $params) {
                        $form->dateRange("{$params}.{$j}.start_date", "{$params}.{$j}.end_date", '起止时间');
                    })->when('=', 2, function (Form $form) use($j, $params) {
                        $form->number("{$params}.{$j}.days", '过去几天')->min(0)->max(180)->default(1);
                    });
                $form->radio("{$params}.{$j}.is_do", '行为触发')->options([1=>'行使该行为', 2=>'未行使该行为'])->default(1);
                $form->html('</div>')->plain();
            }
            $form->html('<div class="event">')->plain();
            $event_options = [];
            if (!empty($info[$params][$j]['event_id'])) {
                $event_options = [$info[$params][$j]['event_id'] => $info[$params][$j]['event_name']];
                $form->hidden("{$params}.{$j}.id");
            }
            $form->select("{$params}.{$j}.event_id", $event_title)->options($event_options)->ajax(url('admin/Ifttt/search_event'))
                ->setElementClass("sel-event");
            $form->number("{$params}.{$j}.count", '次数')->min(0)->default(1);
            $form->html('</div>')->plain();
            $form->html('<div class="condition-add-btn"><span class="add btn btn-success btn-sm"><i class="fa fa-plus"></i>&nbsp;&nbsp;新增属性</span></div>')->plain();
            $form->html('<div class="many_option-condition"><div class="many_option-condition-forms">')->plain();
            for ($i=0;$i<5;$i++) {
                if ($info && isset($info[$params][$j]['attr']) && $i < count($info[$params][$j]['attr'])) {
                    if ($i == 0) {
                        $form->html('<div class="ep-relation" style="display: block;">')->plain();
                        $form->radio("{$params}.{$j}.relation", "属性关系")->options([1=>'且', 2=>'或'])->default(1);
                        $form->html('</div>')->plain();
                    }
                    $form->html('<div class="many_option-condition-form fields-group" data-id="'.$i.'">')->plain();
                } else {
                    if ($i == 0) {
                        $form->html('<div class="ep-relation">')->plain();
                        $form->radio("{$params}.{$j}.relation", "属性关系")->options([1=>'且', 2=>'或'])->default(1);
                        $form->html('</div>')->plain();
                    }
                    $form->html('<div class="many_option-condition-form fields-group" data-id="'.$i.'" style="display: none;">')->plain();
                }
                $form->html('<div class="con_kj">')->plain();
                $form->select("{$params}.{$j}.attr.{$i}.attr_id", '')->options($this->getSelectAttrOption($info[$params][$j]['event_id'] ?? 0))->setWidth(8, 2)->setElementClass("sel-attr");
                $form->select("{$params}.{$j}.attr.{$i}.attr_type", "")
                    ->options(self::EVENT_ATTRIBUTE_TYPE)
                    ->default($info[$params][$j]['attr'][$i]['attr_type'] ?? 5)
                    ->when('notIn', [7, 8], function (Form $form) use($i, $j, $params, $info) {
                        $form->select("{$params}.{$j}.attr.{$i}.attr_con_id", '')
                            ->options($this->getSelectAttrValue($info[$params][$j]['attr'][$i]['attr_id'] ?? 0))
                            ->when('=', -1, function (Form $form) use($i, $j, $params) {
                                $form->text("{$params}.{$j}.attr.{$i}.attr_con", '')->setWidth(12, 0);
                            })->setWidth(12, 0)->setElementClass("sel-attr-val");
                    })->setWidth(3, 2);
                if ($info && isset($info[$params][$j]['attr']) && $i < count($info[$params][$j]['attr'])) {
                    $form->html("<div class='btn-remove'><input type='hidden' name='{$params}[{$j}][attr][{$i}][is_remove]' class='remove form-removed' value='0' />")->plain();
                } else {
                    $form->html("<div class='btn-remove'><input type='hidden' name='{$params}[{$j}][attr][{$i}][is_remove]' class='remove form-removed' value='1' />")->plain();
                }
                $form->html('<span class="remove btn btn-warning pull-left"><i class="fa fa-trash"></i>&nbsp;移除该属性</span></div>')->plain();
                $form->html('</div>')->plain();
                $form->html('</div>')->plain();
            }
            $form->html('</div></div>')->plain();
            $form->html('</div>')->plain();
            $form->html('</div>')->plain();
        }
        $form->html('</div></div>')->plain();
        $form->html('<div class="event-add-btn"><span class="add btn btn-success btn-sm"><i class="fa fa-plus"></i>&nbsp;&nbsp;添加'.$event_title.'</span></div>')->plain();
        $form->html('</div>')->plain();
    }

    private function getSelectAttrOption($event_id)
    {
        if (!$event_id) return [];

        $options = [];
        $attrs = sIfttt::getAttrListByEventId($event_id);
        if ($attrs) {
            $options = array_column($attrs, 'text', 'id');
        }

        return $options;
    }

    private function getSelectAttrValue($attr_id)
    {
        if (!$attr_id) return [];

        $values = sIfttt::getAttrValuesByAttrId($attr_id);
        array_unshift($values, ["id"=>"-1", "text"=>"自定义"]);

        return array_column($values, 'text', 'id');
    }

    public function searchEvent(Request $request)
    {
        $keyword = $request->input('q', '');
        $page = $request->input('page', 1);

        $events = sIfttt::getAllEventList($page, self::PAGE_SIZE, $keyword);

        return response()->json($events);
    }

    public function getAttrList(Request $request)
    {
        $event_id = $request->input('event_id', 0);
        $attrs = sIfttt::getAttrListByEventId($event_id);

        return response()->json($attrs);
    }

    public function getAttrValues(Request $request)
    {
        $attr_id = $request->input('attr_id', 0);
        $values = sIfttt::getAttrValuesByAttrId($attr_id);
        array_unshift($values, ["id"=>"-1", "text"=>"自定义"]);

        return response()->json($values);
    }

    public function getSelectRules(Request $request)
    {
        $rules = sIfttt::getSelectRuleListFromRemote();

        return response()->json($rules);
    }

    public function saveTask(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $data = $this->formatTaskParams($params);
            $result = sIfttt::saveTaskToRemote($data);
            if ($result) {
                if (isset($params['user_profile'])) {
                    AdmOperationModule::addUserProfile($result, $params['user_profile'], PositionRules::MODULE_TYPE_IFTTT_TASK);
                }
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect(url('/admin/Ifttt/task_list'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function editTaskStatus(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = sIfttt::editTaskStatusToRemote($params['id'], $params['status']);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "保存成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "保存失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    private function formatTaskParams($params)
    {
        $data = [];
        if (isset($params['id']) && $params['id']) {
            $data['id'] = $params['id'];
        }
        $data['taskName'] = $params['task_name'];
        $data['businessWay'] = $params['business_way'];
        $data['remark'] = $params['task_desc'];
        $data['taskStartTime'] = $params['task_start_time'] ? strtotime($params['task_start_time']) : 0;
        $data['taskEndTime'] = $params['task_end_time'] ? strtotime($params['task_end_time']) : 0;
        $data['createBy'] = Admin::user()->username;
        if (isset($params['status']) && $params['status'] == sIfttt::TASK_STATUS_ONLINE) {
            if (!empty($params['rule_ids'])) {
                foreach ($params['rule_ids'] as $item) {
                    if ($item['_remove_'] == 0) {
                        $data['ruleList'][] = $item['rule_id'];
                    }
                }
            }
        } else {
            $data['ruleList'] = [];
            if ($params['rule_action'] == 1 && !empty($params['rule_ids'])) {
                foreach ($params['rule_ids'] as $item) {
                    if ($item['_remove_'] == 0) {
                        $data['ruleList'][] = $item['rule_id'];
                    }
                }
            }
            $data['whiteTable'] = $params['whiteTable'];
            $data['pushType'] = $params['trigger_type'];
            $data['dynamicFieldId'] = $params['similarity'];
            $data['timeInterval'] = $params['interval_duration'];
            $data['isDelayTrigger'] = $params['trigger_opportunity'];
            $data['delayTrigger'] = $params['trigger_opportunity'] == 2 ? $params['delay_time'] : 0;
            $data['actionRelate'] = $params['action_relation'];

            switch ($params['trigger_type']) {
                case self::TRIGGER_TYPE_A:
                    $data['eventRuleList'] = $this->formatEventParam($params['e_a'], 'A');
                    break;
                case self::TRIGGER_TYPE_AB:
                    $data['eventRuleList'] = array_merge($this->formatEventParam($params['e_ab_a'], 'A'), $this->formatEventParam($params['e_ab_b'], 'B'));
                    break;
                case self::TRIGGER_TYPE_V:
                    $data['eventRuleList'][] = [
                        "eventType" => 'C',
                        "pageType" => $params['page_type'],
                        "browseTime" => $params['view_duration'],
                    ];
                    break;
            }

            $data['actionList'] = [];
            if (!empty($params['action'])) {
                foreach ($params['action'] as $item) {
                    if ($item['is_remove'] != 0) continue;

                    $row = [];
                    if (isset($item['id']) && $item['id']) {
                        $row['id'] = $item['id'];
                    }
                    $row['timeType'] = $item['duration'];
                    if ($item['duration'] == 1) {
                        $row['startDay'] = $item['start_date'] ? date("Ymd", strtotime($item['start_date'])) : '';
                        $row['endDay'] = $item['end_date'] ? date("Ymd", strtotime($item['end_date'])) : '';
                    } else {
                        $row['dateCnt'] = $item['days'];
                    }
                    $row['isDo'] = $item['is_do'];
                    $row['actionParamRelate'] = $item['relation'];
                    $row['eventId'] = $item['event_id'];
                    $row['cnt'] = $item['count'];
                    $row['iftttParams'] = $this->formatAttrData($item['attr']);
                    $data['actionList'][] = $row;
                }
            }

            if (isset($params['user_profile'])) {
                $data['user_profile'] = $params['user_profile'];
            }
        }

        return $data;
    }

    private function formatTaskInfo($info)
    {
        if (empty($info)) return [];

        $data = [];
        $data['id'] = $info['id'];
        $data['task_name'] = $info['taskName'];
        $data['status'] = $info['status'];
        $data['task_desc'] = $info['remark'];
        $data['business_way'] = $info['businessWay'];
        $data['trigger_type'] = $info['pushType'];
        $data['similarity'] = $info['dynamicFieldId'];
        $data['interval_duration'] = $info['timeInterval'];
        $data['trigger_opportunity'] = $info['isDelayTrigger'];
        $data['delay_time'] = $info['delayTrigger'];
        $data['task_start_time'] = $info['taskStartTime'] ? date("Y-m-d H:i:s", $info['taskStartTime']) : '';
        $data['task_end_time'] = $info['taskEndTime'] ? date("Y-m-d H:i:s", $info['taskEndTime']) : '';
        $data['action_relation'] = $info['actionRelate'];
        $data['trigger_users'] = $info['triggerUnt'];
        $data['is_approve'] = $info['isApprove'];
        $data['rule_ids'] = array_map(function($rule_id) {
            return ['rule_id'=>$rule_id];
        }, $info['ruleList']);
        $data['whiteTable'] = $info['whiteTable'];
        if (!empty($info['eventRuleList'])) {
            foreach ($info['eventRuleList'] as $item) {
                $row = [];
                $row['id'] = $item['id'];
                $row['event_id'] = $item['eventId'];
                $row['event_name'] = $item['eventName'];
                $row['count'] = $item['cnt'];
                $row['relation'] = $item['paramRelate'];
                $row['attr'] = $this->formatInfoAttr($item['iftttParams']);
                if ($info['pushType'] == self::TRIGGER_TYPE_A) {
                    $data['e_a'][] = $row;
                }
                if ($info['pushType'] == self::TRIGGER_TYPE_AB) {
                    if ($item['eventType'] == 'A') {
                        $data['e_ab_a'][] = $row;
                    } else {
                        $data['e_ab_b'][] = $row;
                    }
                }
                if ($info['pushType'] == self::TRIGGER_TYPE_V) {
                    $data['page_type'] = $item['pageType'];
                    $data['view_duration'] = $item['browseTime'];
                }
            }
        }
        $data['action'] = [];
        if (!empty($info['actionList'])) {
            foreach ($info['actionList'] as $item) {
                $row = [];
                $row['id'] = $item['id'];
                $row['duration'] = $item['timeType'];
                $row['start_date'] = $item['startDay'];
                $row['end_date'] = $item['endDay'];
                $row['days'] = $item['dateCnt'];
                $row['is_do'] = $item['isDo'];
                $row['relation'] = $item['actionParamRelate'];
                $row['event_id'] = $item['eventId'];
                $row['event_name'] = $item['eventName'];
                $row['count'] = $item['cnt'];
                $row['attr'] = $this->formatInfoAttr($item['iftttParams']);
                $data['action'][] = $row;
            }
        }
        $data['user_profile'] = AdmOperationModule::getPositionRulesById($info['id'], PositionRules::MODULE_TYPE_IFTTT_TASK, true) ?: [];

        return $data;
    }

    private function formatInfoAttr($params)
    {
        if (empty($params)) return [];

        $attr_data = [];
        foreach ($params as $v) {
            $attr = [];
            $attr['attr_id'] = $v['id'];
            $attr['attr_type'] = $v['sign'];
            if (!$v['valueId']) {
                $attr['attr_con_id'] = -1;
                $attr['attr_con'] = $v['value'];
            } else {
                $attr['attr_con_id'] = $v['valueId'];
            }
            $attr_data[] = $attr;
        }

        return $attr_data;
    }

    public function saveTaskRule(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = false;
            if ($params['rule_action'] == 2) {
                $result = sIfttt::saveTaskRuleToRemote($params);
            }

            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "保存成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "保存失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    public function predictSql(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token'], $params['user_profile']);

            switch ($params['trigger_type']) {
                case self::TRIGGER_TYPE_A:
                    unset($params['e_ab_a'], $params['interval_duration'], $params['e_ab_b'], $params['page_type'], $params['view_duration']);
                    break;
                case self::TRIGGER_TYPE_AB:
                    unset($params['e_a'], $params['page_type'], $params['view_duration']);
                    break;
                case self::TRIGGER_TYPE_V:
                    unset($params['e_a'], $params['e_ab_a'], $params['interval_duration'], $params['e_ab_b']);
                    break;
            }
            $data = $this->formatTaskParams($params);
            $data['sqlResultKey'] = md5($params['taskName']).'_'.uniqid();
            $result = sIfttt::predictSql($data);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "预估中，请耐心等待",
                    'key' => $data['sqlResultKey']
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "预估失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    public function getPredictSqlResult(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $k = $params['key'];
            $result = sIfttt::getPredictSqlResFromRemote($k);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "请求成功",
                    'data' => $result
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "请求失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    private function formatEventParam($params, $event_type)
    {
        if (empty($params)) return [];

        $event_data = [];
        foreach ($params as $item) {
            if ($item['is_remove'] == 0) {
                $row = [];
                if (isset($item['id']) && $item['id']) {
                    $row['id'] = $item['id'];
                }
                $row['eventType'] = $event_type;
                $row['eventId'] = $item['event_id'];
                $row['cnt'] = $item['count'];
                $row['paramRelate'] = $item['relation'];
                $row['iftttParams'] = $this->formatAttrData($item['attr']);
                $event_data[] = $row;
            }
        }

        return $event_data;
    }

    private function formatAttrData($attr)
    {
        if (empty($attr)) return [];

        $attr_data = [];
        foreach ($attr as $v) {
            if ($v['is_remove'] == 0) {
                $attr = [];
                $attr['id'] = $v['attr_id'];
                $attr['sign'] = $v['attr_type'];
                if ($v['attr_con_id'] == '-1') {
                    $attr['value'] = $v['attr_con'];
                } else {
                    $attr['valueId'] = $v['attr_con_id'];
                }
                $attr_data[] = $attr;
            }
        }

        return $attr_data;
    }

    public function taskCheck(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = sIfttt::submitTaskCheck($params['id']);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "提交成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "提交失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    private function addScript()
    {
        return <<<SCRIPT
        $('.condition-add-btn').off('click', '.add').on('click', '.add', function () {
            var vLen = $(this).parent().siblings(".many_option-condition").find(".many_option-condition-form:visible").length;
            $(this).parent().siblings(".many_option-condition").find(".many_option-condition-form").eq(vLen).find(".remove").val(0);
            $(this).parent().siblings(".many_option-condition").find(".many_option-condition-form").eq(vLen).show();
            if ($(this).parent().siblings(".many_option-condition").find(".many_option-condition-form:visible").length > 0) {
                $(this).parent().siblings(".many_option-condition").find(".ep-relation").show();
            }
            if ($(this).parent().siblings(".many_option-condition").find(".many_option-condition-form").length == $(this).parent().siblings(".many_option-condition").find(".many_option-condition-form:visible").length) {
              $(this).hide();
            }
            return false;
        });
        $('.many_option-condition').off('click', '.remove').on('click', '.remove', function () {
            $(this).closest('.many_option-condition-form').find(".remove").val(1);
            $(this).closest('.many_option-condition-form').hide();
            //清空输入值
            $(this).closest('.many_option-condition-form').find("select").val("").select2();
            $(this).closest('.btn-remove').siblings(".cascade-group").children(".cascade-group").find("input").val("");
            $(this).closest('.btn-remove').siblings(".cascade-group").children(".cascade-group").addClass("hide");
            
            $(this).closest('.many_option-condition-form').appendTo($(this).closest(".many_option-condition-forms"));
            if ($(this).closest(".many_option-condition-forms").find(".many_option-condition-form:visible").length == 0) {
                $(this).closest(".many_option-condition-forms").find(".ep-relation").hide();
            }
            if ($(this).closest(".many_option-condition-forms").find('.many_option-condition-form').length > $(this).closest(".many_option-condition-forms").find(".many_option-condition-form:visible").length) {
                $(this).closest(".many_option-condition").siblings(".condition-add-btn").children(".add").show();
            }
            return false;
        });
        
        $('.event-add-btn').off('click', '.add').on('click', '.add', function () {
            var vLen = $(this).parent().siblings(".many_option-event").find(".many_option-event-form:visible").length;
            $(this).parent().siblings(".many_option-event").find(".many_option-event-form").eq(vLen).find(".event-kj>.remove").val(0);
            if (vLen >= 1) {
                var rel = '';
                if ($(this).parent().siblings(".many_option-event").find(".many_option-event-form").eq(vLen).find(".event-kj-title").attr("data-title") == "行为" && $(".action_relation:checked").val() == '1') {
                    rel = '--AND';
                } else {
                    rel = '--OR';
                }
                for (var i=1;i<=vLen;i++) {
                    $(this).parent().siblings(".many_option-event").find(".many_option-event-form").eq(i).find(".event-kj-title").text(rel);
                }
            }
            $(this).parent().siblings(".many_option-event").find(".many_option-event-form").eq(vLen).show();
            if ($(this).parent().siblings(".many_option-event").find(".many_option-event-form").length == $(this).parent().siblings(".many_option-event").find(".many_option-event-form:visible").length) {
              $(this).hide();
            }
            return false;
        });
        
        $('.many_option-event').off('click', '.remove').on('click', '.remove', function () {
            $(this).closest('.many_option-event-form').find(".remove").val(1);
            $(this).closest('.many_option-event-form').hide();
            var event_title = '';
            if ($(this).closest('.many_option-event-form').find(".event-kj-title").attr("data-title") == '事件A') {
                event_title = $(this).closest('.many_option-event-form').find(".event-kj-title").attr("data-title") + ' <i class="fa fa-question-circle" data-type="event-a"></i>';
            } else {
                event_title = $(this).closest('.many_option-event-form').find(".event-kj-title").attr("data-title");
            }
            $(this).closest('.many_option-event-form').find(".event-kj-title").html(event_title);
            var index = $(this).closest('.many_option-event-form').attr("data-id");
            //$("#survey_option_"+index+"_value").val("");
            $(this).closest('.many_option-event-form').appendTo($(this).closest(".many_option-event-forms"));
            if ($(this).closest('.many_option-event-form').length > $(this).closest('.many_option-event-form:visible').length) {
                $(this).closest(".many_option-event").siblings(".event-add-btn").children(".add").show();
            }
            return false;
        });
        
        $(function() {
            getTriggerTypeTip();
            getSimilarityTip();
            
            $(".tab-tips").show();
            
            $(".sel-attr").siblings('.select2').find(".select2-selection__placeholder").text("请选择相关属性");
            $(".sel-attr-val").siblings('.select2').find(".select2-selection__placeholder").text("请选择属性值");
            
            $(".ep-relation").find("label.control-label").html('属性关系 <i class="fa fa-question-circle" data-type="attr-rela"></i>');
            $("label[for=similarity]").html('交互共性 <i class="fa fa-question-circle" data-type="similarity"></i>');
            $("label[for=trigger_opportunity]").html('触发时机 <i class="fa fa-question-circle" data-type="trigger_opportunity"></i>');
            $("input[name=rule_action]:last").parent('div').append(' <i class="fa fa-question-circle" data-type="rule_add"></i>');
            $(".action-duration").find(".form-group:first").find("label.control-label").append(' <i class="fa fa-question-circle" data-type="time_type"></i>');
        });
        
        $("input[name='trigger_type']").unbind('click').on('click',function(){
            getTriggerTypeTip();
        });
        
        $(".similarity").unbind('change').on('change',function(){
            getSimilarityTip();
        });
        
        function getTriggerTypeTip(){
            let checkValue = $("input[name='trigger_type']:checked").val();
            var typeList = {'1':"完成A", '2':"完成A未完成B", '3':"浏览页面"}
            $("#tip1").text(typeList[checkValue]);
        }
        
        function getSimilarityTip(){
            let checkValue = $(".similarity").val();
            if (checkValue>0) {
                var list = {'1':"同一作者", '2':"同一内容", '3':"同一内容类型"}
                $("#tip2").text(list[checkValue]);
                $(".tab-tips").css("top", "0px");
            } else {
                $("#tip2").text('');
                $(".tab-tips").css("top", "5px");
            }
        }
        
        var t = 0;
        
        $('.btn-save-rule').on('click',function(e){
            e.preventDefault();
            var form = $(this).parents('form');
            layer.confirm('确定要保存规则么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                var inputList = form.serializeArray();
                var arr = [];
                for (var i = 0; i < inputList.length; i++) {
                    if (inputList[i].name.indexOf("e_a[") !== -1 
                    || inputList[i].name.indexOf("e_ab_a[") !== -1
                    || inputList[i].name.indexOf("e_ab_b[") !== -1
                    || inputList[i].name.indexOf("user_profile[") !== -1
                    || inputList[i].name.indexOf("action[") !== -1) {
                        continue;
                    }
                    arr.push(inputList[i]);
                }
                $.post("/admin/Ifttt/save_task_rule", arr, function(data){
                    layer.msg(data.message);
                    if (data.status) {
                        setTimeout(function () {
                            $("input[name=rule_action]").closest('.radio-group-toggle').find('label:eq(0)').trigger('click');
                        }, 2000);
                    }
                });
            });
        });
        
        $('.modal-submit button').on('click',function(e){
            e.preventDefault();
            var form = $(this).parents('form');
            layer.confirm('确定要编辑任务状态么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post("/admin/Ifttt/edit_task_status", form.serialize(), function(data){
                    layer.msg(data.message);
                    if (data.status) {
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    }
                });
            });
        });
        
        $('.btn-check').on('click',function(e){
            e.preventDefault();
            var id = $(this).attr("data-id");
            layer.confirm('确定要审核通过当前任务么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post("/admin/Ifttt/edit_task_status", {id:id, status:3}, function(data){
                    if (data.status) {
                        layer.msg("审核成功");
                        $('.btn-check').hide();
                    } else {
                        layer.msg("审核失败");
                    }
                });
            });
        });
        
        $('.sub-check').on('click',function(e){
            e.preventDefault();
            var id = $(this).attr("data-id");
            layer.confirm('确定要提交审批当前任务么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post("/admin/Ifttt/task_check", {id:id}, function(data){
                    layer.msg(data.message);
                    if (data.status) {
                        parent.window.location.reload();
                    }
                });
            });
        });
        
        $.fn.parseForm=function(){
            var o = {};
            var a = this.serializeArray();
            $(a).each(function(){
                if (this.name.indexOf("user_profile") == -1) {
                    if(o[this.name]){
                        if($.isArray(o[this.name])){
                            o[this.name].push(this.value);
                        }else{
                            o[this.name]=[o[this.name],this.value];
                        }
                    }else{
                        o[this.name]=this.value; 
                    }
                }
            });
            return o;
        };
        
        $('.prospect button').on('click',function(e){
            e.preventDefault();
            var form = $(this).parents('form');
            $(this).attr("disabled", "disabled").text("预估中...");
            console.log(form.parseForm());
            $.post("/admin/Ifttt/predict_sql", form.parseForm(), function(data){
                layer.msg(data.message);
                if (data.status) {
                    t = setInterval(function(){
                        $.get("/admin/Ifttt/sql_res?key="+data.key, function(r){
                            if (r.status) {
                                console.log(r.data);
                                if (r.data.status == 1) {
                                    layer.msg("预估成功");
                                    $('.prospect button').removeAttr("disabled").text("预估");
                                    $(".trigger_users").val(r.data.count);
                                    clearInterval(t);
                                }
                            }
                        });
                    }, 5000);
                }
            });
        });
        
        $(document).off('change', ".sel-event");
        $(document).on('change', ".sel-event", function () {
            var target = $(this).closest('.event-kj').find(".sel-attr");
            $.get("/admin/Ifttt/attr_list",{event_id : this.value}, function (data) {
                target.find("option").remove();
                $(target).select2({
                    placeholder: {"id":"","text":"请选择相关属性"},
                    allowClear: true,
                    data: $.map(data, function (d) {
                        d.id = d.id;
                        d.text = d.text;
                        return d;
                    })
                });
                $(target).val("").select2({
                    placeholder: {"id":"","text":"请选择相关属性"}
                });
            });
        });
        
        $(document).off('change', ".sel-attr");
        $(document).on('change', ".sel-attr", function () {
            var target = $(this).closest('.con_kj').find(".sel-attr-val");
            $.get("/admin/Ifttt/get_attr_values",{attr_id : this.value}, function (data) {
                target.find("option").remove();
                $(target).select2({
                    placeholder: {"id":"","text":"请选择属性值"},
                    allowClear: true,
                    data: $.map(data, function (d) {
                        d.id = d.id;
                        d.text = d.text;
                        return d;
                    })
                });
                $(target).val("").select2({
                    placeholder: {"id":"","text":"请选择属性值"}
                });
                $(target).closest('.cascade-group').find(".cascade-group").addClass("hide");
                $(target).closest('.cascade-group').find(".cascade-group").find("input").val("");
            });
        });
        
        $(document).off('change', ".sel-attr-val");
        $(document).on('change', ".sel-attr-val", function () {
            var target = $(this).closest('.cascade-group').find(".cascade-group");
            $(target).removeClass("hide");
            if (this.value == -1) {
                $(target).removeClass("hide");
            } else {
                $(target).addClass("hide");
                $(target).find("input").val("");
            }
        });
        
        $(".nav-tabs li").click(function () {
             let oIndex = $(this).index();
             $("input[name=tab_location]").val(oIndex+1);
        });
        
        $(document).on('mouseover', "i[data-type=event-a]", function () {
            $(this).popover({
                html: true,
                trigger: 'hover',
                title: '事件：',
                content: "1.可以输入关键词自动匹配相关事件，选择事件后可通过下方添加属性对事件更精细的控制；<br/>2.事件与事件属性最多可添加5个；<br/>3.多个A之间的关系为“或”，不可进行更改；<br/>4.可选择的事件为【埋点平台】中维护的事件，如后续想在此平台中选择新的埋点事件，请确保已在【埋点平台】中创建维护。"
            });
        });
        
        $(document).on('mouseover', "i[data-type=attr-rela]", function () {
            $(this).popover({
                html: true,
                trigger: 'hover',
                title: '属性关系：',
                content: "<p style='width: 179px;text-align: justify;'>且：必须同时满足所有属性，当前事件才算完成；<br/>或：满足其中一个属性，当前事件就算完成。</p>"
            });
        });
        
        $(document).on('mouseover', "i[data-type=similarity]", function () {
            $(this).popover({
                html: true,
                trigger: 'hover',
                title: '交互共性：',
                content: "<p style='width: 383px;text-align: justify;'>交互共性主要是针对用户交互对象来说，以用户点赞2次为例：<br/>无：用户随意点赞2个内容即代表完成；<br/>同一作者：用户必须对用一个作者的内容进行点赞2次，才代表完成，如果对作者A、作者B分别点赞一次，则不计入完成；<br/>同一内容：用户不需对同一内容完成2次点赞，才算完成；<br/>同一内容类型：用户需要对相同内容类型的作品完成2次点赞，比如点赞2次的内容都为整屋或者都为note才可以。</p>"
            });
        });
        
        $(document).on('mouseover', "i[data-type=trigger_opportunity]", function () {
            $(this).popover({
                html: true,
                trigger: 'hover',
                title: '触发时机：',
                content: "<p style='width: 326px;text-align: justify;'>立即触发：当用户满足条件后直接触达；<br/>延迟：当用户满足条件后，n秒以后再进行触达。</p>"
            });
        });
        
        $(document).on('mouseover', "i[data-type=rule_add]", function () {
            $("i[data-type=rule_add]").popover({
                html: true,
                trigger: 'click',
                title: '新增规则：',
                content: "<p style='width: 300px;text-align: justify;'>新增规则具体配置操作可以参考 <a href='https://confluence.haohaozhu.me/pages/viewpage.action?pageId=160338089' target='_blank'>IFTTT管理SOP</a> 中IFTTT配置操作手册</p>"
            });
        });
        
        $(document).on('mouseover', "i[data-type=sql_pre]", function () {
            $(this).popover({
                html: true,
                trigger: 'hover',
                title: 'SQL预估：',
                content: "<p style='width: 326px;text-align: justify;'>可以根据【触达时机】与【受众用户】中选择的事件进行sql预估（默认跑昨天的情况）。</p>"
            });
        });
        
        $(document).on('mouseover', "i[data-type=time_type]", function () {
            $(this).popover({
                html: true,
                trigger: 'hover',
                title: '时间类型：',
                content: "<p style='width: 326px;text-align: justify;'>静态：选择一个固定时间，比如说选择了20211230 ~ 20211231号打开app的用户，那么后台就会固定圈选到这个时间范围内的用户；<br/>动态：选择动态时间，过去 n 天，随着时间的变化，其圈选的用户也在不断变化。</p>"
            });
        });
SCRIPT;
    }
}